package conf

import (
	"fmt"
	sgorm "gitee.com/smallow/spirit/lib/gorm"
	"gitee.com/smallow/spirit/webframe"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

var (
	logger               *zap.Logger
	infrastructureConfig = &InfrastructureConfig{}
	mysqlDBConfig        = &mysqlConfig{}
	mysqlDB              *gorm.DB
)

type InfrastructureConfig struct {
	ListenOn  string `json:"listen_on" mapstructure:"listen_on"`
	LogDir    string `json:"log_dir" mapstructure:"log_dir"`
	LogLever  string `json:"log_lever" mapstructure:"log_level"`
	LogPrefix string `json:"log_prefix" mapstructure:"log_prefix"`
}
type mysqlConfig struct {
	DriverName     string `json:"driver_name" mapstructure:"driver_name"`
	DataSourceName string `json:"data_source_name" mapstructure:"data_source_name"`
	MaxOpenConn    int    `json:"max_open_conn" mapstructure:"max_open_conn"`
	MaxIdleConn    int    `json:"max_idle_conn" mapstructure:"max_idle_conn"`
}

func init() {
	_, err := webframe.Viper("./conf/config.toml", infrastructureConfig)
	if err != nil {
		fmt.Errorf("[srpc] init config error:%v", err)
		return
	}
	logger = webframe.InitZapLogger(infrastructureConfig.LogDir, infrastructureConfig.LogPrefix, infrastructureConfig.LogLever, 50, 10, 0, false, false, true, true)
	logger.Info("infrastructure ListenOn:", zap.String("port", infrastructureConfig.ListenOn))

	_, err = webframe.Viper("./conf/mysql.toml", mysqlDBConfig)
	if err != nil {
		logger.Error("mysql DB init config error:%v", zap.Any("mysqlDBConfigErr", err))
		return
	}
	mysqlDB = sgorm.NewGorm(mysqlDBConfig.DataSourceName, mysqlDBConfig.DriverName, mysqlDBConfig.MaxOpenConn, mysqlDBConfig.MaxIdleConn, nil)
	logger.Info("infrastructure DB init successful", zap.String("DNS", mysqlDBConfig.DataSourceName))
	logger.Info("===================>infrastructure init successful!<===================")
}

func Logger() *zap.Logger {
	return logger
}
func GetConf() *InfrastructureConfig {
	return infrastructureConfig
}

func GetMysqlDB() *gorm.DB {
	return mysqlDB
}
